function [w,fmp] = fmp(f,R)
% This function constructs the factor mimicking portfolio using N assets R 
% (R is a T*N matrix) for m factors (f is a T*m matrix)  
[T,m] = size(f); 
[~,N] = size(R);

% 1. Getting rid of nan
a = isnan(R);
b = isnan(f);
a2 = sum(a,2);
b2 = sum(b,2);

a3 = find(a2 == N); %% all returns and factors are absent
b3 = find(b2 == N);

if isempty(a3) == 1 && isempty(b3) == 1
else
   c = max([a3;b3]); 
   R = R(c+1:end,:); % start from the balanced sample
   f = f(c+1:end,:);
   T = T-c;
end


for i = 1:N
    fit2 = fitlm(f,R(:,i));
    beta(:,i) = fit2.Coefficients.Estimate(2:end,1);
end

lambda = nan(T,m);


for i = 1:T
    fit3 = fitlm(beta',R(i,:)','Intercept',false);
    xx = fit3.Coefficients.Estimate;
    lambda(i,:) = xx';
end
fmp = lambda;

% Portfolio weight
w2 = inv(beta*beta')*beta;
w = w2'; % portfolio weight
if isempty(a3) == 1 && isempty(b3) == 1
else
    fmp = [nan(c,m);fmp];
end
